package com.geek.factory.service.impl;

import com.geek.factory.entity.UserRole;
import com.geek.factory.mapper.UserRoleMapper;
import com.geek.factory.service.UserRoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-06-24
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    @Override
    public List<Integer> getRoleIdsByUserId(Integer userId) {
        return this.list(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, userId))
                .stream().map(UserRole::getRoleId).collect(Collectors.toList());
    }

    @Override
    public void saveUserRoles(Integer userId, List<Integer> roleIds) {
        // 先删除原有
        this.removeByUserId(userId);
        // 再批量插入
        if (roleIds != null && !roleIds.isEmpty()) {
            List<UserRole> userRoles = roleIds.stream()
                    .map(roleId -> new UserRole(null, userId, roleId))
                    .collect(Collectors.toList());
            this.saveBatch(userRoles);
        }
    }

    @Override
    public void removeByUserId(Integer userId) {
        this.remove(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, userId));
    }

    @Override
    public List<Integer> getUserIdsByRoleId(Integer roleId) {
        return this.list(new LambdaQueryWrapper<UserRole>().eq(UserRole::getRoleId, roleId))
                .stream().map(UserRole::getUserId).collect(Collectors.toList());
    }
}
